package com.example.obmb.customer.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.obmb.common.base.R;
import com.example.obmb.common.base.ResponseCode;
import com.example.obmb.common.base.PageParams;
import com.example.obmb.common.util.ConstantUtil;
import com.example.obmb.common.util.RestTemplateUtils;
import com.example.obmb.customer.mapper.ICustomerMapper;
import com.example.obmb.customer.service.ICustomerSerivce;
import com.example.obmb.common.entity.CustomerDO;
import com.example.obmb.common.dto.EstatementTypeDTO;
import com.example.obmb.common.entity.StatementInfoDO;
import com.example.obmb.common.entity.StatementPdfDO;
import com.example.obmb.common.vo.StatementInfoResponseVO;
import com.example.obmb.common.vo.StatementInfoVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


import static com.example.obmb.common.util.ConstantUtil.*;

@Slf4j
@Service
public class CustomerServiceImpl implements ICustomerSerivce {

    @Resource
    private ICustomerMapper customerMapper;

    @Autowired
    private RestTemplateUtils restUtil;

    /**
     * 查询投资账户的电子账单选项
     * @param cif 客户号
     * @param productType 产品类型
     * @return 查询列表
     */
    @Override
    public R<Object> getCustomerEstatementType(String cif, String productType) {
        List<EstatementTypeDTO> estatementTypeDTOS = customerMapper.selectEstatementTypeByCifAndProductType(cif,productType);
        return  R.result(ResponseCode.SUCCESS.getCode(), estatementTypeDTOS,"查询成功");
    }

    /**
     * 设定投资账户为电子账单
     * @param customerDO --tradingAcc 户口号码 --isEstatement 是否电子结单(Y/N)
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public  R<Object> modifyCustomerEstatementType(CustomerDO customerDO) {
        try {
            customerMapper.modifyCustomerEstatementType(customerDO);
        }catch (Exception ex){
            log.error("修改客户电子结单类型失败", ex.getMessage());
            return R.result(ResponseCode.BAD_REQUEST.getCode(),"not","修改客户电子结单类型失败！");
        }
        return  R.result(ResponseCode.SUCCESS.getCode(), "success","查询成功");
    }

    public StatementInfoResponseVO queryStatementInfo(PageParams<StatementInfoDO> request) {
        PageHelper.startPage(request.getCurrent(),request.getSize());
        List<StatementInfoVO> statementInfoVOList = customerMapper.queryStatementInfo(request.getModel());
        List<String> tradingAccList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(statementInfoVOList)) {
            tradingAccList = statementInfoVOList.stream().map(StatementInfoVO::getTradingAcc).collect(Collectors.toList());
        }
        StatementInfoResponseVO statementInfoResponseVO = new StatementInfoResponseVO();
        statementInfoResponseVO.setTradingAccList(tradingAccList);
        PageInfo<StatementInfoVO> pageInfo = new PageInfo<>(statementInfoVOList);
        statementInfoResponseVO.setStatementList(pageInfo);
        return statementInfoResponseVO;
    }

    /**
     * 请求P8获取结单PDF文档(P9USD版)
     * @param recordId 结单Id
     * @param response
     * @return
     */
    @Override
    public R<Object> getPdfByP9usd(Long recordId, HttpServletResponse response){
        ServletOutputStream outputStream = null;
        FileInputStream fileInputStream = null;
        try{
            //TODO 调用p8相关接口拿到文件
            fileInputStream = restUtil.post(P8_URL, FileInputStream.class).getBody();
            //打开请求返回流
            outputStream = response.getOutputStream();
            byte[] oBuff = new byte[1024];
            int iSize;
            while(-1 != (iSize = fileInputStream.read(oBuff))){
                //将文件写入到响应流
                outputStream.write(oBuff,0,iSize);
            }
            outputStream.flush();
        }catch (IOException e) {
            log.error("流打开失败!",e.getMessage());
            return new R<>(400,"下载失败，请稍后再试!！");
        }catch (Exception ex){
            log.error("请求P8失败!",ex.getMessage());
            return new R<>(400,"下载失败，请稍后再试!！");
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    log.error("文件流关闭失败！");
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    log.error("返回输出流关闭失败！");
                }
            }

        }
        return new R<>(200,"下载成功！");
    }

    @Override
    public byte[] getPdfByDocumentum(StatementPdfDO statementPdfDO) {
        //TODO 到 documentum取得相關PDF
        return null;
    }
}
